/**
 * 
 */
package com.auction.job.core.schedule;

import com.yisu.auction.ewf.common.spring.SpringContext;
import org.quartz.*;

import java.util.Date;

public class ResumeJob extends BaseJob {

	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		try {
			Scheduler scheduler = SpringContext.getBean("schedulerFactory");
			String[] groupNames = scheduler.getJobGroupNames();
			for (String groupName : groupNames) {
				if(groupName.startsWith("AUCTION")) {
					String[] jobNames = scheduler.getJobNames(groupName);
					for (String jobName : jobNames) {
						JobDataMap dataMap = scheduler.getJobDetail(jobName, groupName).getJobDataMap();
						String prizeId = (String)dataMap.get("prizeId");
						Trigger[] triggers = scheduler.getTriggersOfJob(jobName, groupName);
						for (Trigger trigger : triggers) {
							if(jobName.startsWith("purchase_")) {
								String triggerName = trigger.getName();
								String triggerGroupName = trigger.getGroup();
								int triggerState = scheduler.getTriggerState(triggerName, triggerGroupName);
								if (triggerState == 3) {//ERROR
									QuartzManager.removeJob(jobName);
									QuartzManager.addPurchaseJob(prizeId);
								} else {
									long nextFireDate = trigger.getNextFireTime().getTime();
									long currentDate = new Date().getTime();
									if(((nextFireDate + 2000) <= currentDate) || ((currentDate + 20000) < nextFireDate)) {
										QuartzManager.removeJob(jobName);
										QuartzManager.addPurchaseJob(prizeId);
									}
								}
							}
						}
					}
				}
			}
		} catch (Exception e) {
			LOG.error("Failed to list all jobs, cause: {}", e);
		}
	}

}
